import * as vscode from "vscode";

// https://zhuanlan.zhihu.com/p/405546232
// https://juejin.cn/post/6844903842518171661?searchId=202310071733453E3C2F80AB51D357DCB2#heading-1

const logExt = vscode.commands.registerCommand("wof-demo1.log", () => {
  const currentEditor = vscode.window.activeTextEditor;
  if (!currentEditor) {
    return;
  }
  const reg = /(\S+)(\.log)$/;
  const { selection, document } = currentEditor;

  // # 检查是否按照指定格式按tab键
  const position = document.getWordRangeAtPosition(selection.anchor, reg);
  if (!position) {
    return vscode.window.showInformationMessage(
      "please codeing like this: xxx.log"
    );
  }

  const docText = document.getText(position); // 获取输入的内容
  const tempArr = reg.exec(docText);
  const prefix = tempArr && tempArr[1];
  const replaceText = `console.log('${prefix}: ', ${prefix});`;

  currentEditor
    .edit((editer) => {
      editer.replace(position, replaceText);
    })
    .then(() => {
      const line = position.start.line;
      const index = document.lineAt(line).firstNonWhitespaceCharacterIndex;

      currentEditor.selection = new vscode.Selection(
        new vscode.Position(line, replaceText.length + index),
        new vscode.Position(line, replaceText.length + index)
      );
    });
});

export default logExt;
